package com.lap.auth.adapter.driving.persistence.role.repository;

import com.lap.auth.adapter.driving.persistence.role.RoleCache;
import com.lap.auth.adapter.driving.persistence.role.RoleConverter;
import com.lap.auth.adapter.driving.persistence.role.mapper.RoleMapper;
import com.lap.auth.adapter.driving.persistence.role.po.RolePo;
import com.lap.auth.domain.role.Role;
import com.lap.auth.domain.role.repository.RoleRepository;
import java.util.List;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Repository;

@RequiredArgsConstructor
@Repository
public class RoleRepositoryImpl implements RoleRepository {

  private final RoleConverter converter;
  private final RoleMapper roleMapper;

  @Override
  public Integer save(Role role) {
    RolePo rolePo = converter.toPo(role);
    if (role.isNew()) {
      roleMapper.insert(rolePo);
      return rolePo.getId();
    }
    return roleMapper.updateById(rolePo);
  }

  @CacheEvict(
      value = {RoleCache.ROLE_MENU},
      key = "#id")
  @Override
  public int deleteById(Integer id) {
    return roleMapper.deleteById(id);
  }

  @Override
  public Optional<Role> findById(Integer id) {
    var roleDO = roleMapper.selectById(id);
    return Optional.ofNullable(converter.toDomain(roleDO));
  }

  @Override
  public boolean existsByCode(String code) {
    long count = roleMapper.countByCode(code);
    return count > 0;
  }

  @Override
  public List<Role> findByIds(List<Integer> roleIds) {
    var list = roleMapper.selectByIds(roleIds);
    return converter.toDomains(list);
  }
}
